package com.xindaoapp.happypet.viewpager.windows;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.circle.library.CircularProgressButton;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.Message;
import com.xindaoapp.happypet.protocol.IUploadProgress;
import com.xindaoapp.happypet.protocol.PostQueue;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.KeyValuePair;
import com.xindaoapp.happypet.viewpager.ViewPagerWindow;
import com.xindaoapp.happypet.viewpager.adapter.MyPostAdapter;

/**
 * 我的发表 <br/>
 * 我的回复
 * 
 * @author chenghao
 * 
 */
public class MyPostWindow extends ViewPagerWindow {

    private PullToRefreshListView vPullToRefreshListView;
    private View vLoadingView;
    /** 顶部发表进度条 */
    private LinearLayout vTopUnPublishContainer;

    private final int mTabIndex;

    public MyPostWindow(Activity context, int tabIndex) {
        super(context);
        mTabIndex = tabIndex;
    }

    @Override
    protected View onCreateView() {
        return View.inflate(getBaseContext(), R.layout.layout_listview, null);
    }

    @Override
    protected void initViews() {
        super.initViews();
        vLoadingView = getView().findViewById(R.id.loading);
        vPullToRefreshListView = (PullToRefreshListView) getView().findViewById(R.id.listview);
        vPullToRefreshListView.setOnRefreshListener(mOnRefreshListener);
    }

    private final OnRefreshListener<ListView> mOnRefreshListener =
            new OnRefreshListener<ListView>() {

                @Override
                public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                    onLoadDatas();
                }
            };

    @Override
    protected void onLoadDatas() {
        initListHeaderView();
        if (mTabIndex == 0) {
            loadMyPost();
        } else if (mTabIndex == 1) {
            loadMyReply();
        }
    }

    private void loadMyReply() {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .getMyReply(UserState.getUserUid(), Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                        new IRequest<List<Message>>() {

                            @Override
                            public void request(List<Message> t) {
                                if (null != t) {

                                    vPullToRefreshListView.setAdapter(new MyPostAdapter(
                                            getBaseContext(), t, Constants.PAGE_SIZE,
                                            R.layout.menu_message_item, R.layout.item_loading,
                                            mTabIndex));

                                    if (t.size() == 0) {
                                        onNoDataArrived();
                                    }
                                    vPullToRefreshListView.onRefreshComplete();
                                    vLoadingView.setVisibility(View.GONE);
                                } else {
                                    onDataArrived(false);
                                }
                            }
                        });
    }

    private void initListHeaderView() {
        if (mTabIndex == 0) {
            vPullToRefreshListView.getRefreshableView().addHeaderView(
                    getHeaderView(getMyPostQueue()));
        } else if (mTabIndex == 1) {
            vPullToRefreshListView.getRefreshableView().addHeaderView(
                    getHeaderView(getMyReplyQueue()));
        }
        vPullToRefreshListView.setAdapter(new MyPostAdapter(getBaseContext(),
                new ArrayList<Message>(), Constants.PAGE_SIZE, R.layout.menu_message_item,
                R.layout.item_loading, mTabIndex));
    }

    private void loadMyPost() {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .getMyPost(UserState.getUserUid(), Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                        new IRequest<List<Message>>() {

                            @Override
                            public void request(List<Message> t) {
                                if (null != t) {
                                    vPullToRefreshListView.setAdapter(new MyPostAdapter(
                                            getBaseContext(), t, Constants.PAGE_SIZE,
                                            R.layout.menu_message_item, R.layout.item_loading,
                                            mTabIndex));
                                }
                                vPullToRefreshListView.onRefreshComplete();
                                vLoadingView.setVisibility(View.GONE);
                            }
                        });
    }

    /**
     * 我的发表队列
     * 
     * @return
     */
    private List<PostQueue> getMyPostQueue() {
        List<PostQueue> postQueueImpls = new ArrayList<PostQueue>();
        // 解析队列里面数据是发表还是回复
        for (int i = 0; i < HappyPetApplication.get().getUploaQueueImpl().getPostQueue().size(); i++) {
            if (TextUtils.isEmpty(HappyPetApplication.get().getUploaQueueImpl().getPostQueue()
                    .get(i).getPostInfo().tid)) {
                postQueueImpls.add(HappyPetApplication.get().getUploaQueueImpl().getPostQueue()
                        .get(i));
            }
        }

        return postQueueImpls;
    }

    /**
     * 我的回复队列
     * 
     * @return
     */
    private List<PostQueue> getMyReplyQueue() {
        List<PostQueue> postQueueImpls = new ArrayList<PostQueue>();
        // 解析队列里面数据是发表还是回复
        for (int i = 0; i < HappyPetApplication.get().getUploaQueueImpl().getPostQueue().size(); i++) {
            if (!TextUtils.isEmpty(HappyPetApplication.get().getUploaQueueImpl().getPostQueue()
                    .get(i).getPostInfo().tid)) {
                postQueueImpls.add(HappyPetApplication.get().getUploaQueueImpl().getPostQueue()
                        .get(i));
            }
        }
        return postQueueImpls;
    }

    /**
     * 获取需要重新提交的队列
     * 
     * @param list
     * @return
     */
    private View getHeaderView(List<PostQueue> list) {
        if (vTopUnPublishContainer == null) {
            vTopUnPublishContainer =
                    (LinearLayout) View.inflate(getBaseContext(), R.layout.layout_top_post, null);
        }
        vTopUnPublishContainer.removeAllViews();
        holders = new ViewHolder[list.size()];
        for (int i = 0; i < list.size(); i++) {
            final PostQueue info = list.get(i);
            final View item = View.inflate(getBaseContext(), R.layout.item_top_post, null);
            holders[i] = new ViewHolder();
            holders[i].icon = (ImageView) item.findViewById(R.id.icon);
            if (null != info.getSendingInfo() && info.getSendingInfo().second == 0) {
                ImageLoader.getInstance().displayImage("file://" + info.getSendingInfo().first,
                        holders[i].icon);
            } else if (null != info.getSendingInfo() && info.getSendingInfo().second == 1) {
                ImageLoader.getInstance().displayImage("file://" + info.getPostInfo().videoCover,
                        holders[i].icon);
            } else if (info.getPostInfo().sendingArray.size() > 0) {
                KeyValuePair<String, Integer> pair = info.getPostInfo().sendingArray.get(0);
                if (pair.second == 0) {
                    ImageLoader.getInstance().displayImage("file://" + pair.first, holders[i].icon);
                } else if (pair.second == 1) {
                    ImageLoader.getInstance().displayImage(
                            "file://" + info.getPostInfo().videoCover, holders[i].icon);
                }
            }
            holders[i].plan = (TextView) item.findViewById(R.id.plan);
            holders[i].name = (TextView) item.findViewById(R.id.name);
            holders[i].btnUpload = (ImageView) item.findViewById(R.id.btn_upload);
            holders[i].progressBar = (CircularProgressButton) item.findViewById(R.id.progress);
            holders[i].container = item.findViewById(R.id.r_top);
            holders[i].name.setText(TextUtils.isEmpty(info.getPostInfo().title) ? info
                    .getPostInfo().content : info.getPostInfo().title);
            if (info.isRunning()) {// 如果是正在发帖，则添加监听器
                info.addListener(new uploadProgress(info, holders[i]));
                holders[i].progressBar.setProgress(1);
                resetSendState(holders[i], true);
            } else {
                resetSendState(holders[i], false);
            }

            final int temp = i;
            holders[i].btnUpload.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    resetSendState(holders[temp], true);
                    info.start(new uploadProgress(info, holders[temp]));
                }
            });
            vTopUnPublishContainer.addView(item);
        }
        return vTopUnPublishContainer;
    }

    private void resetSendState(ViewHolder holder, boolean isSending) {
        if (isSending) {
            holder.btnUpload.setEnabled(false);
            holder.btnUpload.setImageResource(R.drawable.btn_uploading);
        } else {
            holder.btnUpload.setEnabled(true);
            holder.btnUpload.setImageResource(R.drawable.btn_upload_android);
        }
    }

    class uploadProgress implements IUploadProgress {
        ViewHolder holder;
        PostQueue info;

        public uploadProgress(PostQueue info, ViewHolder holder) {
            super();
            this.holder = holder;
            this.info = info;
        }

        @Override
        public void success() {
            getHeaderView(getMyPostQueue());

            // 刷新当前列表


            if (mTabIndex == 0) {
                getHeaderView(getMyPostQueue());
                loadMyPost();
            } else if (mTabIndex == 1) {
                getHeaderView(getMyReplyQueue());
                loadMyReply();
            }
        }

        @Override
        public void start(int current, int count) {
            if (count == 0) {
                holder.plan.setText(String.format("正在发送...", current, count));
            } else {
                holder.plan.setText(String.format("正在发送：%s / %s", current, count));
                KeyValuePair<String, Integer> pair =
                        info.getPostInfo().sendingArray.get(current - 1);
                if (pair.second == 0) {
                    ImageLoader.getInstance().displayImage("file://" + pair.first, holder.icon);
                } else if (pair.second == 1) {
                    ImageLoader.getInstance().displayImage(
                            "file://" + info.getPostInfo().videoCover, holder.icon);
                }
            }
        }

        @Override
        public void progress(int progress) {
            holder.progressBar.setProgress(progress);
        }

        @Override
        public void pause() {}

        @Override
        public void error(String msg) {
            holder.plan.setText("");
            resetSendState(holder, false);
        }

        @Override
        public void cancel() {}
    }

    private ViewHolder[] holders;

    class ViewHolder {
        View container;
        ImageView icon;
        TextView plan;
        TextView name;
        ImageView btnUpload;
        CircularProgressButton progressBar;
    }
}
